package com.example.chamberlainserver.Service.impl;

import com.example.chamberlainserver.Entry.Department;
import com.example.chamberlainserver.Entry.Role;
import com.example.chamberlainserver.Entry.User;
import com.example.chamberlainserver.Service.DepartmentService;
import com.example.chamberlainserver.Service.UserRoleService;
import com.example.chamberlainserver.Service.UserService;
import com.example.chamberlainserver.Vo.Request.User.UserQuery;
import com.example.chamberlainserver.dto.PageResult;
import com.example.chamberlainserver.mapper.UserMapper;
import com.example.chamberlainserver.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private UserRoleService userRoleService;
    
    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public boolean addUser(User user) {
        return userMapper.insertUser(user) > 0;
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    @Override
    public User getUserByStuNo(String stuNo) {
        return userMapper.getUserByStuNo(stuNo);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.getAllUsers();
    }

    @Override
    public List<User> getUsersByRole(String role) {
        return userMapper.getUsersByRole(role);
    }

    @Override
    public boolean updateUser(User user) {
        System.out.println("UserServiceImpl.updateUser - 开始更新用户: " + user.getId());
        System.out.println("UserServiceImpl.updateUser - 用户角色数据: " + user.getRoles());
        
        int result = userMapper.updateUser(user);
        System.out.println("UserServiceImpl.updateUser - 用户基本信息更新结果: " + result);
        
        // 如果用户基本信息更新成功且包含角色信息，则更新用户角色关联
        if (result > 0 && user.getRoles() != null && !user.getRoles().isEmpty()) {
            System.out.println("UserServiceImpl.updateUser - 开始处理角色更新，角色数量: " + user.getRoles().size());
            
            // 根据角色代码查询角色ID列表
            List<Integer> roleIds = new ArrayList<>();
            for (Role role : user.getRoles()) {
                System.out.println("UserServiceImpl.updateUser - 处理角色: " + role);
                if (role.getRoleCode() != null) {
                    System.out.println("UserServiceImpl.updateUser - 根据角色代码查询: " + role.getRoleCode());
                    // 根据角色代码查询角色信息
                    Role dbRole = roleMapper.getRoleByCode(role.getRoleCode());
                    if (dbRole != null) {
                        System.out.println("UserServiceImpl.updateUser - 找到角色: " + dbRole.getId() + ", " + dbRole.getRoleName());
                        roleIds.add(dbRole.getId());
                    } else {
                        System.out.println("UserServiceImpl.updateUser - 未找到角色代码: " + role.getRoleCode());
                    }
                } else if (role.getId() != null) {
                    // 如果直接提供了角色ID，也支持
                    System.out.println("UserServiceImpl.updateUser - 使用角色ID: " + role.getId());
                    roleIds.add(role.getId());
                }
            }
            
            System.out.println("UserServiceImpl.updateUser - 最终角色ID列表: " + roleIds);
            
            // 更新用户角色关联
            if (!roleIds.isEmpty()) {
                boolean roleUpdateResult = userRoleService.assignRolesToUser(user.getId(), roleIds);
                System.out.println("UserServiceImpl.updateUser - 角色更新结果: " + roleUpdateResult);
            } else {
                System.out.println("UserServiceImpl.updateUser - 角色ID列表为空，跳过角色更新");
            }
        } else {
            System.out.println("UserServiceImpl.updateUser - 跳过角色更新，原因: result=" + result + ", roles=" + user.getRoles());
        }
        
        return result > 0;
    }

    @Override
    public boolean deleteUser(Integer id) {
        return userMapper.deleteUserById(id) > 0;
    }
    
    @Override
    public PageResult<User> getPagedUserList(UserQuery userQuery) {
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        
        // 分页参数
        params.put("offset", (userQuery.getCurrent() - 1) * userQuery.getPageSize());
        params.put("limit", userQuery.getPageSize());
        
        // 查询条件
        if (userQuery.getUserName() != null && !userQuery.getUserName().isEmpty()) {
            params.put("userName", "%" + userQuery.getUserName() + "%");
        }
        
        if (userQuery.getName() != null && !userQuery.getName().isEmpty()) {
            params.put("name", "%" + userQuery.getName() + "%");
        }
        
        if (userQuery.getNickName() != null && !userQuery.getNickName().isEmpty()) {
            params.put("nickName", "%" + userQuery.getNickName() + "%");
        }
        
        if (userQuery.getEmail() != null && !userQuery.getEmail().isEmpty()) {
            params.put("email", "%" + userQuery.getEmail() + "%");
        }
        
        if (userQuery.getPhone() != null && !userQuery.getPhone().isEmpty()) {
            params.put("phone", "%" + userQuery.getPhone() + "%");
        }
        
        if (userQuery.getRole() != null && !userQuery.getRole().isEmpty()) {
            params.put("role", userQuery.getRole());
        }
        
        if (userQuery.getStatus() != null && !userQuery.getStatus().isEmpty()) {
            params.put("status", userQuery.getStatus());
        }
        
        if (userQuery.getStartDate() != null && !userQuery.getStartDate().isEmpty()) {
            params.put("startDate", userQuery.getStartDate());
        }
        
        if (userQuery.getEndDate() != null && !userQuery.getEndDate().isEmpty()) {
            params.put("endDate", userQuery.getEndDate());
        }
        
        // 查询总记录数
        Long total = userMapper.getPagedUserCount(params);
        
        // 查询数据列表
        List<User> users = userMapper.getPagedUserList(params);
        
        // 为每个用户加载角色信息和部门信息
        users.forEach(user -> {
            // 移除敏感信息
            user.setPassword(null);
            // 加载用户角色信息
            List<Role> roles = userRoleService.getRolesByUserId(user.getId());
            user.setRoles(roles);
            // 加载用户部门信息
            if (user.getDepartmentId() != null) {
                Department department = departmentService.getDepartmentById(user.getDepartmentId());
                user.setDepartment(department);
            }
        });
        
        // 返回分页结果
        return new PageResult<>(userQuery.getCurrent(), userQuery.getPageSize(), total, users);
    }

    @Override
    public List<Role> getUserRoles(Integer userId) {
        return userRoleService.getRolesByUserId(userId);
    }
}